package mqlistener

import (
	log "ac-common-go/glog"
	"ac-julink/cache"
	"ac-julink/manager"
	config_blacklist "ac-julink/tool/config_blacklist"
	"ac-julink/tool/util"
	"encoding/json"
	"errors"
	"github.com/go-stomp/stomp"
)

func NewBlackListNCleanCacheListener() *BlackListNCleanCacheListener {
	return &BlackListNCleanCacheListener{}
}

type BlackListNCleanCacheListener struct {
}

func (self *BlackListNCleanCacheListener) OnReceive(msg *stomp.Message, context *cache.SyncContext, client *manager.AcRestClient) (err error) {
	defer func() {
		if pErr := recover(); pErr != nil {
			log.Errorf("BlackListNCleanCacheListener OnReceive panic:%+v\n%s", pErr, util.PanicTrace())
		}
	}()
	if msg == nil || msg.Body == nil {
		return errors.New("stomp.Message invalid")
	}
	log.Infof("BlackListNCleanCacheListener MQ OnReceive:%s", string(msg.Body))

	if err := DealBlackListNCleanCacheMsg(string(msg.Body), context); err != nil {
		log.Errorf("DealBlackListNCleanCache failed !%+v", err)
		return err
	}
	return nil
}

type BlackListNCleanCacheMsg struct {
	Type string `json:"type"`
	Data string `json:"data"`
}

type CleanCacheData struct {
	WifiIdList string `json:"wifiIdList"`
}

func DealBlackListNCleanCacheMsg(_jsonstr string, context *cache.SyncContext) error {
	var m BlackListNCleanCacheMsg
	var k CleanCacheData
	if err := json.Unmarshal([]byte(_jsonstr), &m); err != nil {
		log.Error("parse BlackListNCleanCache msg failed! ", err)
		return err
	}

	if m.Type == "_BLACK_LIST_" {
		config_blacklist.Init()
	} else if m.Type == "_CLEAN_CACHE_" {
		if err := json.Unmarshal([]byte(m.Data), &k); err != nil {
			log.Error("parse CleanCacheData failed! ", err)
			return err
		}
		log.Infof("begin to delete cache for %s", k.WifiIdList)
		context.DeleteBatch(k.WifiIdList)
		log.Infof("succeed to delete cache for %s", k.WifiIdList)
	}

	return nil
}
